package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.feigns.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDTO;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    BehaviorFeign behaviorFeign;

    /**
     * 保存用户搜索历史记录
     * @param userSearchDto
     */
    @Async("taskExecutor")
    @Override
    public void insert(UserSearchDTO userSearchDto) {
        ResponseResult<ApBehaviorEntry> result = behaviorFeign.findByUserIdOrEquipmentId(userSearchDto.getUserId(), userSearchDto.getEquipmentId());
        if (!result.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用行为服务失败");
        }
        ApBehaviorEntry behaviorEntry = result.getData();
        if (behaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"行为实体数据不存在");
        }
        ApUserSearch userSearch = mongoTemplate.findOne(Query.query(Criteria.where("entryId").is(behaviorEntry.getId()).and("keyword").is(userSearchDto.getSearchWords())), ApUserSearch.class);
        if (userSearch != null){
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);
        }else{
            userSearch = new ApUserSearch();
            userSearch.setEntryId(behaviorEntry.getId());
            userSearch.setKeyword(userSearchDto.getSearchWords());
            userSearch.setCreatedTime(new Date());
            mongoTemplate.insert(userSearch);
        }
    }

    /**
     * 查询用户搜索历史记录  显示10条
     * @param userSearchDto
     * @return
     */
    @Override
    public ResponseResult findUserSearch(UserSearchDTO userSearchDto) {
        if(userSearchDto.getMinBehotTime() == null){
            userSearchDto.setMinBehotTime(new Date());
        }
        ApUser user = AppThreadLocalUtils.getUser();
        //1 查询实体 60ed86609d88f41a1da5e770
        ResponseResult<ApBehaviorEntry> behaviorResult = behaviorFeign.findByUserIdOrEquipmentId(user==null?null:user.getId(), userSearchDto.getEquipmentId());
        if (!behaviorResult.checkCode()){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"远程调用行为服务失败");
        }
        ApBehaviorEntry apBehaviorEntry = behaviorResult.getData();
        if (apBehaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"行为实体数据不存在");
        }
        // 查询当前用户的搜索列表  按照时间倒序 .limit(userSearchDto.getPageSize())
        List<ApUserSearch> userSearchList = mongoTemplate.find(Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId()).and("createdTime").lt(userSearchDto.getMinBehotTime())).with(Sort.by(Sort.Direction.DESC, "createdTime")).limit(10), ApUserSearch.class);
        return ResponseResult.okResult(userSearchList);
    }

    /**
     * 删除搜索历史
     * @param historySearchDto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDTO historySearchDto) {
        ApUser user = AppThreadLocalUtils.getUser();
        ResponseResult<ApBehaviorEntry> behaviorEntryResult = behaviorFeign.findByUserIdOrEquipmentId(user == null ? null : user.getId(), historySearchDto.getEquipmentId());
        if(!behaviorEntryResult.checkCode()){
            return ResponseResult.errorResult(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用行为服务失败");
        }
        ApBehaviorEntry behaviorEntry = behaviorEntryResult.getData();
        if(behaviorEntry == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "行为实体数据不存在");
        }
        mongoTemplate.remove(Query.query(Criteria.where("_id").is(historySearchDto.getId()).and("entryId").is(behaviorEntry.getId())),ApUserSearch.class);
        return ResponseResult.okResult();
    }
}
